import {Component,OnInit} from '@angular/core'
import {Hero} from './hero'
import {HeroService} from './hero.service'
import {Router,ParamMap} from '@angular/router'
@Component({
    selector:'my-heroes',
    templateUrl:'./heroes.component.html',
    styleUrls:['./heroes.component.css']
})

export class HeroesComponent implements OnInit{
    selectedHero:Hero;
    heroes:Hero[];

    constructor(private heroeService:HeroService,private router:Router){}
    ngOnInit():void{
        this.getHeroes();
    }
    getHeroes():void{
        this.heroeService.getHeroes().then(res=>this.heroes=res)
    }
    onSelect(hero:Hero):void{
        this.selectedHero = hero;
    }
    gotoDetail():void{
        this.router.navigate(['/detail',this.selectedHero.id])
    }
    add(name:string):void{
        name = name.trim();
        if(!name){return;}
        this.heroeService.create(name)
        .then(hero=>{
            this.heroes.push(hero);
            this.selectedHero = null;
        });
    }
    delete(hero:Hero):void{
        this.heroeService.delete(hero.id).then(res=>{
            this.heroes = this.heroes.filter(h=>h!=hero)
            if(this.selectedHero === hero){
                this.selectedHero = null;
            }
        })
    }
} 